package top.lucky.redishmdp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.lucky.redishmdp.dto.LoginFormDTO;
import top.lucky.redishmdp.dto.Result;
import top.lucky.redishmdp.dto.UserDTO;
import top.lucky.redishmdp.entity.User;
import top.lucky.redishmdp.mapper.UserMapper;
import top.lucky.redishmdp.service.UserService;
import top.lucky.redishmdp.utils.RedisConstants;
import top.lucky.redishmdp.utils.RegexUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Jane
 * @date 2022/5/24, 10:40
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendSmsCode(String phone, HttpSession session) {

        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不符合返回错误
            return Result.fail("手机号格式错误");
        }
        //3.符合生成验证码
        String smsCode = RandomUtil.randomNumbers(6);
        //4.保存验证码到session
        //session.setAttribute("code",smsCode);
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, smsCode, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送
        log.info("发送验证码成功:{}",smsCode);
        //6.返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        //2.校验验证码
        //从redis中获取验证码并校验
        String smsCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (smsCode == null || !smsCode.equals(loginForm.getCode())) {
            return Result.fail("验证码校验失败");
        }
        //3.判断用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //4.创建用户
            user = createUserWithPhone(phone);
        }
        //4.保存用户信息到redis
        //随机生成token,作为登陆令牌
        String token = UUID.randomUUID().toString(true);
        //user对象转为hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("USER_" + RandomUtil.randomNumbers(10));
        save(user);
        return user;
    }
}
